<?php
/**
 * Created by PhpStorm.
 * User: jack Wang
 * Date: 2021/12/17
 * Time: 14:29
 */

require "vendor/autoload.php";

use \Elasticsearch\ClientBuilder;
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
use Elasticsearch\Common\Exceptions\Missing404Exception;

//封装es工具类
class Es
{
    private $client = [];

    //构造函数中连接Es
    public function __construct()
    {
        $this->client = ClientBuilder::create()->setHosts(config_item('esHost'))->build();
    }

    public function getEs()
    {
        return $this->client;
    }

    /**
     * 创建索引
     * @param string $indexName 索引名
     * @param int $number_of_shards 分区数
     * @param int $number_of_replicas 分片数
     * @param array $data 字段数组
     * @return array
     */
    public function createIndex($indexName = "", $number_of_shards = 5, $number_of_replicas = 1, $data = [])
    {
        // 创建索引
        $params = [
            'index' => $indexName,
            'body' => [
                'settings' => [
                    'number_of_shards' => $number_of_shards,
                    'number_of_replicas' => $number_of_replicas
                ],
                'mappings' => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => $data
                ]
            ]
        ];
        try {
            $response = $this->client->indices()->create($params);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (BadRequest400Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }

    /**
     * 删除索引
     * @param string $indexName 索引名
     */
    public function delIndex($indexName = "")
    {
        $data = ['index' => $indexName];
        try {
            $response = $this->client->indices()->delete($data);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (Missing404Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }

    /**
     * @param string $indexName 索引名
     * @param int $id 新增、修改的文档id
     * @param array $data 新增、修改的文档数据
     */
    public function SaveDoc($indexName = "", int $id, $data = [])
    {
        // 写文档
        $params = [
            'index' => $indexName,
            'type' => '_doc',
            'id' => $id,
            'body' => $data,
        ];

        try {
            $response = $this->client->index($params);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (Missing404Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }

    /**
     * @param string $indexName 索引名
     * @param int $id 文档id
     * @return array
     */
    public function deleteDoc($indexName = "", int $id)
    {
        $data = [
            'index' => $indexName,
            'id' => $id,
        ];
        try {
            $response = $this->client->delete($data);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (Missing404Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }

    /**
     * @param string $indexName
     * @param int $id
     * @param array $data
     * @return array
     */
    public function updateDoc($indexName = "", int $id, $data = [])
    {
        //修改指定索引指定文档的内容
        $params = [
            //索引
            'index' => $indexName,
            //类型 es6之后一个索引对应一个type
            'type' => '_doc',
            //文档id
            'id' => $id,
            //字段值
            'body' => [
                'doc' => [
                    $data
                ]
            ],
        ];
        try {
            $response = $this->client->update($params);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (Missing404Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }

    /**
     * @param string $indexName
     * @param array $body
     * @return array
     */
    public function searchDoc($indexName = "", $body =[])
    {
        $params = [
            'index' => $indexName,
            'body' => $body,
        ];
        try {
            $response = $this->client->search($params);
            $res = [
                'code' => 200,
                'message' => "success",
                'data' => $response
            ];
        } catch (Missing404Exception $exception) {
            $res = [
                'code' => $exception->getCode(),
                'message' => json_decode($exception->getMessage(), true),
                'data' => [],
            ];
        }
        return $res;
    }
}